﻿using Ocelot.Configuration;
using Ocelot.Configuration.Repository;
using Ocelot.Middleware;
using Ocelot.Provider.Nacos.NacosClient.V2;
using Ocelot.Responses;

namespace Service.Gateway.Core.AgileConfigServiceDiscovery
{
    public class AgileConfigurationProvider
    {
        public static OcelotMiddlewareConfigurationDelegate Get { get; } = GetAsync;


        private static async Task GetAsync(IApplicationBuilder builder)
        {
            IInternalConfigurationRepository internalConfigRepo = builder.ApplicationServices.GetService<IInternalConfigurationRepository>();
            Response<IInternalConfiguration> config = internalConfigRepo.Get();
            IHostApplicationLifetime hostLifetime = builder.ApplicationServices.GetService<IHostApplicationLifetime>();
            if (UsingAgileConfigServiceDiscoveryProvider(config.Data))
            {
                await builder.UseNacosAspNet(hostLifetime);
            }
        }

        private static bool UsingAgileConfigServiceDiscoveryProvider(IInternalConfiguration configuration)
        {
            return configuration?.ServiceProviderConfiguration != null && configuration.ServiceProviderConfiguration.Type?.ToLower() == "agilegonfig";
        }
    }

}
